import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/login/index.vue'
import Layout from '@/views/layout/index.vue'
import Dashboard from '@/views/dashboard/index.vue'
import Article from '@/views/article/index.vue'
import { getToken } from '@/utils/storage'
import { Message } from 'element-ui'

Vue.use(VueRouter)

// const routes = [
// ]

const router = new VueRouter({
  routes: [
    { path: '/login', component: Login },
    {
      path: '/',
      component: Layout,
      redirect: 'dashboard',
      children: [
        { path: 'dashboard', component: Dashboard },
        { path: 'article', component: Article }
      ]
    }
  ]
})

// 设置页面访问权限
// 定义一个白名单 不管有没有都可以跳转到登录页
const whiteList = ['/login']
router.beforeEach((to, from, next) => {
  // ...
  // console.log(to)
  // 白名单直接放行
  if (whiteList.includes(to.path)) {
    next()
    return
  }
  const token = getToken()
  // 如果有token就放行
  if (token) {
    next()
    return
  }

  // 没有token就跳转到登录页，提示用户登录
  Message.info('请先登录信息')
  next('/login')
})

export default router
